import React, { Component } from 'react'
import ReactDom from 'react-dom';
import PaginationTable from 'components/PaginationTable'
// import {BpmButtonSubmit,BpmButtonRecall} from 'yyuap-bpm';
import { actions } from 'mirrorx';
import { Popover,Icon,Button,Message,Modal, Loading,Table,Checkbox,Col,Row,FormControl,Label,Form,Pagination } from 'tinper-bee';
import multiSelect from "tinper-bee/lib/multiSelect.js";;
import Select from 'bee-select';
import moment from "moment/moment";
import Viewer from 'react-viewer';
import 'react-viewer/dist/index.css';
import Header from 'components/Header';
import AcceptancePaperForm from '../acceptancePaper-form';
import AcExport from '../acceptancePaper-export';
import filterColumn from "tinper-bee/lib/filterColumn.js";
import { deepClone } from "utils";
import './index.less'

const FormItem = Form.FormItem;
let MultiSelectTable  = multiSelect(Table, Checkbox);
const FilterColumnTable = filterColumn(Table, Popover, Icon);

export default class AcceptancePaperPaginationTable extends Component {
    constructor(props){
        super(props);
        let self=this;
        this.state = {
            // 表格中所选中的数据，拿到后可以去进行增删改查
            step: 10,
            showModal:false,
            searchValues:{},
            delData:[],
            imgList: [],
            visibleView:false,
            selectData:[],
            column:[
                {
                    title: "序列号",
                    dataIndex: "serialNo",
                    key: "serialNo",
                    width: 100
                },
                {
                    title: "物料品种",
                    dataIndex: "materialVariety",
                    key: "materialVariety",
                    width: 200
                },
                {
                    title: "质量等级",
                    dataIndex: "qualityGrade",
                    key: "qualityGrade",
                    width: 150
                },
                {
                    title: "已检人数",
                    dataIndex: "inspectedPersonNo",
                    key: "inspectedPersonNo",
                    width: 100
                },{
                    title: "平均含水分比(%)",
                    dataIndex: "averageWaterRatio",
                    key: "averageWaterRatio",
                    width: 150
                },{
                    title: "平均扣水分重(吨)",
                    dataIndex: "averageDewateringWeight",
                    key: "averageDewateringWeight",
                    width: 150
                },{
                    title: "平均含杂质比(%)",
                    dataIndex: "averageImpurityRatio",
                    key: "averageImpurityRatio",
                    width: 150
                },{
                    title: "平均含杂质重(吨)",
                    dataIndex: "averageImpurityWeight",
                    key: "averageImpurityWeight",
                    width: 150
                },{
                    title: "平均单价(元)",
                    dataIndex: "averageUnit",//averageUnitPrice
                    key: "averageUnit",
                    width: 150
                }
                // ,{
                //     title: "操作",
                //     dataIndex: "d",
                //     key: "d",
                //     width:100,
                //     fixed: "right",
                //     render(text, record, index) {
                //         return (
                //             <div className='operation-btn'>
                //                 <i size='sm' className='uf uf-search edit-btn' onClick={() => { self.cellClick(record,2) }}></i>
                //                 <i size='sm' className='uf uf-pencil edit-btn' onClick={() => { self.cellClick(record,1) }}></i>
                //             </div>
                //         )
                //     }
                // }
            ]
        }
    }
    
    componentDidMount(){
        // this.setState({ step: this.props.pageSize })
        actions.acceptancePaper.loadList(this.props.queryParam);//table数据
    }
    /**
     * 编辑,详情，增加
     */

    cellClick = async (record,btnFlag) => {
        let id = "";
        if(record){
            id = record["id"];
        }
        if(btnFlag == 2) {
            actions.routing.push(
                {
                    pathname: 'acceptanceChildPaper-edit',
                    search:`?search_id=${id}&btnFlag=${btnFlag}`
                }
            )
        }
    }

    // 删除操作
    confirVerify = (record, index) => {
        this.setState({
            showModal:true,
            VerfiyObj:{ id: record.id,serialNo: record.serialNo }
        });

    }

    onRowClickData = (data,index) => {
        let serialNo = data.serialNo;//id
        let param = {
            serialNo:serialNo
        }
        actions.acceptancePaper.loadChildList(param);//table数据
        this.setState({currentIndex:index,serialNo:serialNo})
    }

    // 分页单页数据条数选择函数
    onPageSizeSelect = (index, value) => {
        let queryParam = deepClone(this.props.queryParam);
        let {pageIndex, pageSize} = queryParam.pageParams;
        pageSize = value;
        queryParam['pageParams'] = { pageIndex, pageSize };
        actions.acceptancePaper.loadList(queryParam);
    }

    onPageIndexSelect = (value, type) => {
        let queryParam = deepClone(this.props.queryParam);
        let { pageIndex, pageSize } = queryParam.pageParams;
        pageIndex = value - 1;

        //let { pageIndex, pageSize } = getPageParam(value, type, queryParam.pageParams);
        queryParam['pageParams'] = { pageIndex, pageSize };
        this.setState({ selectedIndex: 0 }); //默认选中第一行
        actions.acceptancePaper.loadList(queryParam);
    }

    searchValuesCall = (value) => {
        this.setState({
            searchValues:value
        })
    }
    // 模态框确认删除
    onModalDel = async (delFlag)=>{
        let {VerfiyObj,serialNo} = this.state;
        let reason = ReactDom.findDOMNode(this.refs.reason).value;        
        VerfiyObj.modifierReason = reason;
        debugger;
        if(delFlag){
            await actions.acceptancePaper.confirmVerifyItem(VerfiyObj);
            await actions.acceptancePaper.loadChildList({serialNo})
        }
        this.setState({
            showModal:false,
            delData:[]
        })
    }
    // 模板下载
    onLoadTemplate = () => {
        window.open(`${GROBAL_HTTP_CTX}/jx_acceptancePaper/excelTemplateDownload`)
    }

    // 导入成功回调函数
    handlerUploadSuccess = (data)=>{
        // 导入成功后，列表加载数据
        Message.create({content: '导入数据成功', color: 'success'});
        actions.acceptancePaper.loadList();
    }

    // 导入删除回调函数
    handlerUploadDelete = (file) => {

    }

    // 导出
    exportExcel = () =>{
        //actions.acceptancePaper.exportExcel(this.queryParams);
        let {selectData}  = this.state;
        if(selectData.length > 0) {
            actions.acceptancePaper.exportExcel({
                dataList : selectData
            });
        }else {
            Message.create({ content: '请选择导出数据', color : 'danger'  });
        }
    }

    // 打印数据
    printExcel = ()=>{
        let {selectData}  = this.state;
        if(!selectData.length)  
        {
            Message.create({ content: '请选择需打印的数据', color : 'danger'  });
            return;
        }
        actions.acceptancePaper.printExcel({
            queryParams:
            {
                funccode: 'acceptancePaper',
                nodekey: '002'
            },
            printParams: 
            {
                id:selectData[0].id
            }
        });
    }

    showView = (data) => {
        this.setState({
            visibleView:true,
            imgList:data
        })
    }

    // 动态设置列表滚动条x坐标
    getCloumnsScroll = (columns) => {
        let sum = 0;
        columns.forEach((da) => {
            sum += da.width;
        })
        return (sum);
    }

    onTableSelectedData = (data,index) => {
        this.setState({selectData:data})
        
      };


       // <PaginationTable
       //                  data={list}
       //                  pageIndex={pageIndex}
       //                  pageSize={pageSize}
       //                  totalPages={totalPages}
       //                  rowClassName={(record,index,indent)=>{
       //                    if (index == currentIndex) {
       //                        return 'selected';
       //                    } else {
       //                        return '';
       //                    }
       //                  }}
       //                  total = {total}
       //                  columns={this.state.column}
       //                  checkMinSize={6}
       //                  onRowClick={this.onRowClickData}
       //                  onTableSelectedData={this.onTableSelectedData}
       //                  onPageSizeSelect={this.onPageSizeSelect}
       //                  onPageIndexSelect={this.onPageIndexSelect}
       //          />
      
    render(){
        const self=this;
        let {childList, list, showLoading, pageIndex, pageSize, totalPages , total,queryParam } = this.props;
        let {showModal,currentIndex,column,selectData,visibleView,imgList} = this.state;
        let exportProps = { total, pageIndex, pageSize, list,queryParam};
        let columnchild = [
                {
                    title: "检验员",
                    dataIndex: "inspectorName",
                    key: "inspectorName",
                    width: 150
                },
                {
                    title: "检验点",
                    dataIndex: "checkPointName",
                    key: "checkPointName",
                    width: 150
                },{
                    title: "堆号",
                    dataIndex: "heapName",
                    key: "heapName",
                    width: 100
                },{
                    title: "开包件数",
                    dataIndex: "unpackNo",
                    key: "unpackNo",
                    width: 100
                },{
                    title: "检验时间",
                    dataIndex: "inspectorTime",
                    key: "inspectorTime",
                    width: 150
                },{
                    title: "单价(元)",
                    dataIndex: "unit",
                    key: "unit",
                    width: 100
                },{
                    title: "含水分比-测水仪(%)",
                    dataIndex: "waterRatioMeter",
                    key: "waterRatioMeter",
                    width: 150
                },{
                    title: "检验照片",
                    dataIndex: "imgUrls",
                    key: "imgUrls",
                    render: function(text,record,index) {
                        if(!text) return <div></div>;

                        return <img className="monitor-img" src={text[0]} onClick={() => {self.showView(text)}} />
                    }
                },{
                    title: "含水分比-人工(%)",
                    dataIndex: "waterRatioArtificial",
                    key: "waterRatioArtificial",
                    width: 150
                },{
                    title: "扣水分重(吨)",
                    dataIndex: "buckleWaterWeight",
                    key: "buckleWaterWeight",
                    width: 150
                },{
                    title: "含杂质比(%)",
                    dataIndex: "impurityRatio",
                    key: "impurityRatio",
                    width: 150
                },{
                    title: "扣杂质重(吨)",
                    dataIndex: "impurityWeight",
                    key: "impurityWeight",
                    width: 150
                },{
                    title: "退货",
                    dataIndex: "returnGoods",
                    key: "returnGoods",
                    width: 100
                },{
                    title: "退货原因",
                    dataIndex: "returnGoodsReason",
                    key: "returnGoodsReason",
                    width: 150
                },{
                    title: "是否重检",
                    dataIndex: "isReinspection",
                    key: "isReinspection",
                    width: 100
                },{
                    title: "修改人姓名",
                    dataIndex: "modifyuser",
                    key: "modifyuser",
                },,{
                    title: "重检原因",
                    dataIndex: "modifierReason",
                    key: "modifierReason",
                },{
                    title: "叉车工工号",
                    dataIndex: "forkliftWorkerNo",
                    key: "forkliftWorkerNo",
                    width: 100
                },{
                    title: "操作",
                    dataIndex: "d",
                    key: "d",
                    width:100,
                    fixed: "right",
                    render(text, record, index) {
                        return (
                            <div className='operation-btn'>
                                <i size='sm' className='uf uf-search edit-btn' onClick={() => { self.cellClick(record,2) }}></i>
                                {!(record.dr==1 && record.isReinspection=='是') && <span className="rechecked-icon" onClick={() => { self.confirVerify(record,1) }}>重检</span>}
                            </div>
                        )
                    }
                }
            ]
        

        return (
            <div className='acceptancePaper-root'>
                <AcceptancePaperForm  { ...this.props }/>
                <Table
                    data={list}
                    columns={column}
                    onRowClick={this.onRowClickData}
                    dragborder={true} 
                    rowClassName={(record,index,indent)=>{
                        if (index == currentIndex) {
                            return 'selected';
                        } else {
                            return '';
                        }
                      }}
                    draggable={true} 
                    rowKey={(r, i) => i}
                    getSelectedDataFunc={this.onTableSelectedData}
                />

                <div className='pagination'>
                    <Pagination
                        first
                        last
                        prev
                        next
                        boundaryLinks
                        items={totalPages}
                        activePage={pageIndex}
                        onDataNumSelect={this.onPageSizeSelect}
                        onSelect={this.onPageIndexSelect}
                        showJump={true}
                        dataNum={pageSize}
                        maxButtons={5}
                        total={total}
                    />
                </div>

                <h4>检验明细</h4>

                <FilterColumnTable
                        scroll={{y: 150 }} 
                        rowClassName={(record,index,indent)=>{
                          if (record.dr==1 && record.isReinspection=='是') {
                              return 'selected';
                          } else {
                              return '';
                          }
                        }}
                        data={childList}
                        columns={columnchild}
                        checkMinSize={6}
                />

                
                <Loading show={showLoading} loadingType="line" />
                <Modal
                        show={showModal}
                        onHide={this.close} >
                    <Modal.Header>
                        <Modal.Title>确认重检</Modal.Title>
                    </Modal.Header>

                    <Modal.Body>
                        <Col md={7}>
                            <FormItem>
                                <Label>重检原因</Label>
                                <FormControl ref='reason' />
                            </FormItem>
                        </Col>
                    </Modal.Body>

                    <Modal.Footer>
                        <Button onClick={()=>this.onModalDel(false)} shape="border" style={{ marginRight: 50 }}>关闭</Button>
                        <Button onClick={()=>this.onModalDel(true)} colors="primary">确认</Button>
                    </Modal.Footer>
                </Modal>
                <Viewer
                    visible={visibleView}
                    onClose={() => { this.setState({ visibleView: false }); } }
                    images={imgList.map((li) => {
                        return {
                            src: `${li}`
                        }
                    }) }
                />
            </div>

        )

    }
}